<template>
  <div class="wrap">
    <div style="display:flex">
      <van-search v-model="keyword" placeholder="请输入报告编号" clearable @search="onSearch" @clear="onClear"></van-search>
      <van-search v-model="date" placeholder="日期" clearable show-action @clear="onClearDate">
        <template #action>
          <div @click="open">选择</div>
        </template>
      </van-search>
    </div>
    <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
      <div class="list-wrap">
        <div class="list-wrap-item" v-for="item in list" :key="item" @click="toPage(item)">
          <van-cell-group>
            <van-cell title="日期" :value="item.dbilldate" />
            <van-cell title="报告编号" :value="item.orderno" />
            <van-cell title="客户" :value="item.custname" />
          </van-cell-group>
        </div>
      </div>
    </van-list>
    <van-popup v-model:show="show" round position="bottom">
      <van-picker :columns="columns" @cancel="show = false" @confirm="onConfirm" />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onActivated, onDeactivated } from "vue";
import { useRoute, useRouter } from "vue-router";
import { showConfirmDialog, showToast, showLoadingToast, closeToast } from 'vant'
import service from "@/api";
const keyword = ref("");
const list = ref([]);
const loading = ref(false);
const finished = ref(true);
const activeNames = ref(["1"]);

// 添加缓存标识
const cachedData = ref(null);

const route = useRoute();
const router = useRouter();

const show = ref(false)
const date = ref('');

// 用户openId
let openId = route?.query?.openId || "";
// 用户路由页,默认跳到订单页面

if (!openId) {
  let src = window.location.href;
  let index = src.indexOf("?");
  if (index > 0) {
    let dataStr = src.substring(src.indexOf("?") + 1);
    let dataArray = dataStr.split("&");

    dataArray.forEach((str) => {
      let param = str.split("=");
      if (param[0] == "openId") {
        openId = param[1];
      }
    });
  }
}

// 保存搜索条件的键名
const SEARCH_STORAGE_KEY = 'listPageSearchConditions';

// 从本地存储恢复搜索条件
const restoreSearchConditions = () => {
  const savedConditions = localStorage.getItem(SEARCH_STORAGE_KEY);
  if (savedConditions) {
    try {
      const conditions = JSON.parse(savedConditions);
      keyword.value = conditions.keyword || '';
      date.value = conditions.date || '';
    } catch (e) {
      console.error('解析搜索条件失败', e);
    }
  }
};

// 保存搜索条件到本地存储
const saveSearchConditions = () => {
  const conditions = {
    keyword: keyword.value,
    date: date.value
  };
  localStorage.setItem(SEARCH_STORAGE_KEY, JSON.stringify(conditions));
};

// 清除保存的搜索条件
const clearSavedSearchConditions = () => {
  localStorage.removeItem(SEARCH_STORAGE_KEY);
};

const formatDate = (date) => {
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
};

// 修改 onLoad 方法，添加缓存逻辑
const onLoad = async (useCache = true) => {
  // 如果有缓存数据且需要使用缓存，则直接使用缓存数据
  if (cachedData.value && useCache) {
    list.value = cachedData.value;
    finished.value = true;
    return;
  }

  showLoadingToast({
    duration: 0,
    forbidClick: true,
    message: '查询中',
  });
  try {
    const res = service
      .queryOrders({
        itype: "saleorder_query", //订单查询
        info: {
          orderNo: keyword.value,
          cyearmonth: date.value || '',
          openId: openId,
        },
      })
      .then((res) => {
        console.log(res);
        closeToast()
        if (res.status == "success") {
          list.value = res.data;
          // 缓存数据
          cachedData.value = res.data;
        } else {
          closeToast()
          showToast(res.message);
        }
      });
    finished.value = true;
  } catch (error) {
    console.error('绑定请求失败：', error)
  }
};

// 页面被激活时调用（从其他页面返回时）
onActivated(() => {
  // 使用缓存数据，不重新请求
  onLoad(true);
});

const onSearch = (val) => {
  // 搜索时清除缓存，重新请求
  cachedData.value = null;
  saveSearchConditions();
  onLoad(false)
}

const onClear = () => {
  keyword.value = ''
  // 清除缓存，重新请求
  cachedData.value = null;
  saveSearchConditions();
  onLoad(false)
};

const onClearDate = () => {
  date.value = ''
  // 清除缓存，重新请求
  cachedData.value = null;
  saveSearchConditions();
  onLoad(false)
}

const open = () => {
  show.value = true;
}

const onConfirm = (e) => {
  const { selectedValues } = e
  show.value = false;
  date.value = selectedValues[0] + '-' + selectedValues[1]
  // 清除缓存，重新请求
  cachedData.value = null;
  saveSearchConditions();
  onLoad(false)
};

const toPage = (item) => {
  // 路由跳转到卡片页面
  router.push({
    path: "/card",
    query: {
      orderno: item.orderno,
      openId: openId
    }
  });
};

const columns = ref([
  // 第一列
  [],
  // 第二列
  [
    { text: '1月', value: '01' },
    { text: '2月', value: '02' },
    { text: '3月', value: '03' },
    { text: '4月', value: '04' },
    { text: '5月', value: '05' },
    { text: '6月', value: '06' },
    { text: '7月', value: '07' },
    { text: '8月', value: '08' },
    { text: '9月', value: '09' },
    { text: '10月', value: '10' },
    { text: '11月', value: '11' },
    { text: '12月', value: '12' },
  ],
]);

function getYearsRange() {
  const currentYear = new Date().getFullYear();
  return [
    { text: (currentYear - 1).toString(), value: (currentYear - 1).toString() },
    { text: currentYear.toString(), value: currentYear.toString() },
    { text: (currentYear + 1).toString(), value: (currentYear + 1).toString() }
  ];
}

getYearsRange()
columns.value[0] = getYearsRange();

// 组件挂载时恢复搜索条件
restoreSearchConditions();

// 页面失活时保存搜索条件
onDeactivated(() => {
  saveSearchConditions();
});

// 组件卸载前保存搜索条件
window.addEventListener('beforeunload', saveSearchConditions);
</script>

<style scoped lang="css">
#app {
  padding: 0;
}

body {
  display: block;
}

.wrap {
  padding: 0;
  width: 100vw;
  height: 100vh;
  background-color: #F5F5F5;
}

.list-wrap {
  padding: 12px;
}

.list-wrap {
  ::v-deep .van-cell .van-cell__title {
    flex: 0 0 20%;
    text-align: left;
  }

  ::v-deep .van-cell .van-cell__value {
    flex: 0 0 80%;
  }
}

.list-wrap-item {
  margin-bottom: 12px;
}

.title-wrap {
  width: 120px;
  text-align: left;
}
</style>